﻿using System;
using System.Collections.Generic;
using System.Linq;

using Csla;
using Csla.Rules;
using Csla.Rules.CommonRules;

using Haushaltsbuch.DataAcces;
using Haushaltsbuch.DataAcces.Entities;

namespace Haushaltsbuch.Domain.Users
{
    public class UserInfoList : ReadOnlyListBase<UserInfoList, UserInfo>
    {
        public static UserInfoList Get()
        {
            return DataPortal.Fetch<UserInfoList>();
        }

        

        public UserInfoList() {}

        private static void AddObjectAuthorizationRules()
        {
            BusinessRules.AddRule(typeof(UserInfoList), new IsInRole(AuthorizationActions.GetObject, "Admin"));
        }
        
        private void DataPortal_Fetch()
        {
            using (var ctx = new HaushaltsbuchContext())
            {
                IQueryable<User> entities = ctx.Users;

                var children = entities.ToArray().Select(UserInfo.Get);

                this.IsReadOnly = false;
                this.RaiseListChangedEvents = false;

                this.AddRange(children);

                this.IsReadOnly = true;
                this.RaiseListChangedEvents = true;
            }
        }
    }
}